'use strict';

import React from 'react';
import Radium from 'radium';
import { JsonEditor } from 'react-json-edit';
import Controller from './Controller';

@Radium
class TemplateStyleEditor extends React.Component {
  state : {
    returnToMenu : ()=>void;
  };

  constructor(props) {
    super(props);

    this._key = 1;
    this.state = {};
    (this : any).callback = this.callback.bind(this);
    (this : any).save = this.save.bind(this);
    (this : any).query = this.query.bind(this);

  }

  callback(changes) {
    this.setState({json: changes});
  }

  save() {
    if(!this.refs.id.value || !this.refs.id.value || !this.state.json)
      return;

    Controller.updateTemplate(this.refs.id.value, this.refs.item.value, this.state.json);
  }

  query() {
    if(!this.refs.id.value || !this.refs.item.value)
      return;

    this._key++;
    this.setState({ json : Controller.getTemplate(this.refs.id.value, this.refs.item.value) });
  }

  render() {
    return (
      <div style={{width: '100%', height: '100%'}}>
        <div style={{cursor: 'pointer', padding: '20px', marginBottom: '50px'}} onClick={this.props.returnToMenu}>
          <span><i className="fa fa-angle-left m-r-5" />返回</span>
        </div>
        <div style={{padding: '20px'}}><span style={{marginRight: '10px'}}>id:</span><input ref="id" type="input" /></div>
        <div style={{padding: '20px'}}><span style={{marginRight: '10px'}}>item:</span><input ref="item" type="input" /></div>
        <div style={{padding: '50px'}} >
          <button className="btn btn-primary" onClick={this.query}>查询</button>
        </div>
        <div style={{padding: '20px'}}>
          <JsonEditor key={this._key} value={this.state.json} propagateChanges={this.callback}/>
        </div>
        <div style={{padding: '50px'}} >
          <button className="btn btn-primary" onClick={this.save}>确定</button>
        </div>
      </div>
    );
  }
};

module.exports=TemplateStyleEditor;
